package server.server02;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 多线程处理，加入分发器
 */
public class Server07 {
    private ServerSocket serverCocket;
    private boolean isRunning;
    public static void main(String[] args) {
        Server07 server = new Server07();
        server.start();
    }
//启动服务
    public void start(){
        try {
            serverCocket = new ServerSocket(8777);
            isRunning =true;
            receive();
        } catch (IOException e) {
            System.out.println("服务器启动失败");
             e.printStackTrace();
             stop();
        }
    }
//接受连接
    public void receive(){
        while (isRunning) {
            try {
                System.out.println("一个客户端建立了连接");
                Socket client = serverCocket.accept();
                //多线程处理
                new Thread(new Dispatcher(client)).start();
            } catch (IOException e) {
                System.out.println("客户端错误");
                e.printStackTrace();
            }
        }
    }
//停止服务
    public void stop(){
        isRunning=false;
        try {
            this.serverCocket.close();
            System.out.println("服务器已停止");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
